'''
Copyright 2013 Matthew Ramina

This file is part of The Time Machine.

    The Time Machine is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    The Time Machine is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with The Time Machine.  If not, see <http://www.gnu.org/licenses/>.
'''
import os
import glob
import re
import csv


class Game(object):
    def __init__(self):
        self.intro = """
        You go to room 140 during lunch and notice a cute door above the room. You climb the lockers, open the door and enter. You see high tech stuff and monitors and something covered in a drape. What is it?
        
        You uncover it. This thing is labeled \"Time Machine\". Next to it is a keypad, with what looks like a time and coordinates written on its display. It says \"01/01/1970 0000 00.0000 00.0000\".
        
        Which time/place would you like to visit?
        """
        self.questions = []

    def searchText(self):
        self.coordList = []
        self.fileList = []
        """looks at every text file in games/"""
        for infile in glob.glob(os.path.join('games/', "*.txt")):
            file = open(infile, "r")
            for line in file.readlines():
                if "coords" in line:
                    """finds those with coords and take the stuff in quotes"""
                    coords = re.findall('"([^"]*)"', line)
                    self.fileList.append(infile)
                    break
            file.close()
            self.coordList.append(coords[0])
        self.rooms = {}
        return self.coordList  # list of possible coordinates to visit

    def parser(self, command):  # parser that doesn't do much yet...
        command = command.lower()
        parseList = {1: ["a", "1", "y"],  # "" for pressing enter.
                     2: ["b", "2", "n"],
                     3: ["c", "3"],
                     4: ["d", "4"],
                     5: [""]}
        # k is key, v is list, i is item in list
        for (k, v) in parseList.items():
            for i in v:
                if i == command:
                    return k

    def nextCommand(self, command):  # runs on every command typed
        if len(self.questions) == 0:  # very first time run (coordinate select)
            try:
                file = open(self.fileList[command - 1])
            except:
                return
            for line in file.readlines():
                if "q" == line[0]:
                    """finds q and takes stuff in quotes"""
                    csvfile = re.findall('"([^"]*)"', line)
            file.close()

            csvfile = "games/{}".format(csvfile[0])
            """opens the corresponding csv"""
            cv = csv.reader(open(csvfile, "r"))
            for i, row in enumerate(cv):  # builds list of questions
                self.questions.append([row[0], row[1], [row[2], int(row[3])]])
                if row[4] != "":
                    self.questions[i].append([row[4], int(row[5])])
                if row[6] != "":
                    self.questions[i].append([row[6], int(row[7])])
                if row[8] != "":
                    self.questions[i].append([row[8], int(row[9])])

            # print(self.questions)

            self.currentQuestion = self.questions[0]
            if len(self.currentQuestion) == 3:
                return [self.currentQuestion[0], self.currentQuestion[1], [], [], [], [], ["Press enter to continue", self.currentQuestion[2][1]]]
            return self.currentQuestion

        elif command == 9001:  # if you die
            return "death"

        elif command == 9002:
            return "win"

        elif isinstance(command, int):
            self.currentQuestion = self.questions[command - 1]
            if len(self.currentQuestion) == 3:
                return [self.currentQuestion[0], self.currentQuestion[1], [], [], [], [], ["Press enter to continue", self.currentQuestion[2][1]]]
            return self.currentQuestion  # returns the next question


    def reset(self):
        self.questions = []

    # TODO: Some form of save? Possible with shelve module
    # http://inventwithpython.com/blog/2012/05/03/implement-a-save-game-feature-in-python-with-the-shelve-module/
